package com.victor9ac.tfm.web.threadpool;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.springframework.stereotype.Component;

import com.victor9ac.tfm.mashup.connector.port.MashupConnector;
import com.victor9ac.tfm.web.exception.MashupTimeoutException;

@Component
public class MashupThreadPool {
	
    
    ExecutorService threadPool;
    long threadPoolTimeout;
    int threadPoolSize;
	
    public MashupThreadPool(long threadPoolTimeout,int threadPoolSize){
    	this.threadPoolTimeout = threadPoolTimeout;
    	this.threadPoolSize = threadPoolSize;
		threadPool = Executors.newFixedThreadPool(threadPoolSize);
    }
    
    
    public <T> T getResult(Future<T> futureTask) throws MashupTimeoutException{
    	T res = null;
    	try {
			res = futureTask.get(threadPoolTimeout, TimeUnit.MILLISECONDS);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();			
			throw new MashupTimeoutException(e,"Mashup WS is responding too slow");

		}
    	return res;
    }

    
	public <T> Future<T> invoke (MashupConnector connector,String name, Class<T> classGiven){		
		
		Callable<T> commentCallableTask = new MashupTask<T>(connector, name, classGiven);

		Future<T> futureCommentTask = threadPool.submit(commentCallableTask);
		
		
		
		
		return futureCommentTask;
	}
	
}
